//
//  UIColor+SJAdd.swift
//  SJSwiftKit
//
//  Created by swordjoy on 2017/2/16.
//  Copyright © 2017年 swordjoy. All rights reserved.
//

import UIKit

extension UIColor  {
  
  /// 非RGB颜色空间 [UIColor grayColor]就不能用这个方法了！
  public var rgb: (r: CGFloat, g: CGFloat, b: CGFloat) {
    let numOfComponents = self.cgColor.numberOfComponents
    if 4 != numOfComponents {
      fatalError("Must set color: UIColor(red: , green: , blue: , alpha: )")
    }
    if let componemts = self.cgColor.components {
      return (r: componemts[0], g: componemts[1], b: componemts[2])
    }
    fatalError("Must set color: UIColor(red: , green: , blue: , alpha: )")
  }
  
  public static func hex(_ string: String, alpha: CGFloat = 1.0) -> UIColor {
    var cString: String = string.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines).uppercased()
    
    if (cString.hasPrefix("#")) {
      cString = cString.sj.cut(from: 1)
    }
    
    let rString = cString.sj.cut(to: 2)
    let gString = cString.sj.cutString(location: 2, length: 2)
    let bString = cString.sj.cutString(location: 4, length: 2)
    
    var r: CUnsignedInt = 0, g: CUnsignedInt = 0, b: CUnsignedInt = 0;
    Scanner(string: rString).scanHexInt32(&r)
    Scanner(string: gString).scanHexInt32(&g)
    Scanner(string: bString).scanHexInt32(&b)
    
    return UIColor(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: alpha)
  }
  
  public static func hex(_ string: String) -> UIColor {
    return hex(string, alpha: 1.0)
  }
}
